<!DOCTYPE html>
<html lang="en">
<head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <title>zTreeTest</title>

    <link rel="stylesheet" href="../../js/zTree/css/zTreeStyle/zTreeStyle.css" type="text/css">
    <script type="text/javascript" src="../../js/zTree/js/jquery-1.4.4.min.js"></script>
    <script type="text/javascript" src="../../js/zTree/js/jquery.ztree.core.js"></script>
    <script type="text/javascript" src="../../js/zTree/js/jquery.ztree.exedit.js"></script>
    <script type="text/javascript" src="../../js/zTree/js/jquery.ztree.excheck.js"></script>
    <script type="text/javascript" src="../../js/util/UUIDUtils.js"></script>
    <style>
        /* add按钮显示bug*/
        .ztree li span.button.add {
            margin-left: 2px;
            margin-right: -1px;
            background-position: -144px 0;
            vertical-align: top;
            *vertical-align: middle
        }
    </style>
    <script language="JavaScript">
        var table;
        /* 整合layui */
        // layui.use(['form','layer','table'], function () {
        //     var $ = layui.jquery,
        //         form = layui.form;
        //     table = layui.table;
        // })

        // 参考地址http://www.treejs.cn/v3/demo.php#_101
        var zTreeObj;
        // zTree 的参数配置，深入使用请参考 API 文档（setting 配置详解）
        var setting = {
            view: {
                addHoverDom: addHoverDom,
                removeHoverDom: removeHoverDom,
                selectedMulti: false
            },
            data: {
                simpleData: {
                    enable: false, // 设置是否启用简单数据格式（zTree支持标准数据格式跟简单数据格式，上面例子中是标准数据格式）
                    idKey: "id",  // 设置启用简单数据格式时id对应的属性名称
                    pidKey: "pId" // 设置启用简单数据格式时parentId对应的属性名称,ztree根据id及pid层级关系构建树结构
                }
            },
            edit: {
                enable: true,
                editNameSelectAll: true,
                showRemoveBtn: showRemoveBtn,
                showRenameBtn: showRenameBtn

            },
            callback: {
                beforeRemove: beforeRemove,    // 用于捕获节点被删除之前的事件回调函数，并且根据返回值确定是否允许删除操作
                //onRemove: onRemove,    // 用于捕获删除节点之后的事件回调函数。
                beforeRename: beforeRename, // 用于捕获节点编辑名称结束（Input 失去焦点 或 按下 Enter 键）之后，
                // 更新节点名称数据之前的事件回调函数，并且根据返回值确定是否允许更改名称的操作
                //onRename: onRename,    // 用于捕获节点编辑名称结束之后的事件回调函数
                onClick: onClick
            }

        };
        // zTree 的数据属性，深入使用请参考 API 文档（zTreeNode 节点数据详解）
        var zNodes = [
            {
                id: 1, pid: -1, name: "test1", open: true, children: [
                    {id: 2, pid: 1, name: "test1_1"}, {id: 3, pid: 1, name: "test1_2"}]
            },
            {
                id: 4, pid: -1, name: "test2", open: true, children: [
                    {id: 5, pid: 4, name: "test2_1"}, {id: 6, pid: 4, name: "test2_2"}]
            }
        ];

        $(document).ready(function () {
            /* 默认加载节点信息 */
            // getNodesMethod();
            zTreeObj = $.fn.zTree.init($("#treeDemo"), setting, zNodes);
            var nodes = zTreeObj.getNodes();
            if (nodes.length>0) {
                zTreeObj.expandNode(nodes[0], true, true, true);
            }
        });


        function showRemoveBtn(treeId, treeNode) {
            return !(treeNode.id == 0);
        }

        function showRenameBtn(treeId, treeNode) {
            return !(treeNode.id == 0);
        }

        function beforeRemove(treeId, treeNode) {
            return confirm("确认删除 节点 -- " + treeNode.name + " 吗？");
        }

        function beforeRename(treeId, treeNode, newName, isCancel) {
            //新名称为空时提示名称不能为空
            if (newName.length == 0) {
                setTimeout(function () {
                    var zTree = $.fn.zTree.getZTreeObj("treeDemo");
                    zTree.cancelEditName();
                    alert("节点名称不能为空.");
                }, 200);
                return false;
            }

            var Cnodes = getPeerNodes(treeNode);
            //获取当前节点的同级兄弟节点，不包含本节点
            function getPeerNodes(targetNode) {
                if (targetNode == null) {
                    return null;
                } else {
                    if (targetNode.getParentNode() != null) {
                        return targetNode.getParentNode().children;
                    }
                    return null;
                }
            }
            for (var n in Cnodes) {
                if (Cnodes[n].name == newName) {
                    if (Cnodes[n].id == treeNode.id) return;
                    setTimeout(function () {
                        //var zTree = $.fn.zTree.getZTreeObj("treeDemo");
                        //zTree.cancelEditName();
                        alert("节点名称已存在！");
                    }, 200)
                    return false;
                }
            }
            return true;
        }

        function onRemove(event, treeId, treeNode) {
            removeMethod(treeNode)
        }

        function onRename(event, treeId, treeNode, isCancel) {
            console.log(treeNode)
            renameMethod(treeNode)
        }

        function onClick(event, treeId, treeNode){
            // table.reload("menuListTable",{
            //     page: {
            //         curr: 1 // 重新从第1页开始
            //     },
            //     where: {
            //         pid: treeNode.id  // 搜索关键字
            //     }
            // })
        }

        // 用于当鼠标移动到节点上时，显示用户自定义控件，显示隐藏状态同 zTree 内部的编辑、删除按钮
        var newCount = 1;
        function addHoverDom(treeId, treeNode) {
            var sObj = $("#" + treeNode.tId + "_span");
            if (treeNode.editNameFlag || $("#addBtn_" + treeNode.tId).length > 0) return;
            var addStr = "<span class='button add' id='addBtn_" + treeNode.tId
                + "' title='add node' onfocus='this.blur();'></span>";
            sObj.after(addStr);
            var btn = $("#addBtn_" + treeNode.tId);
            if (btn) btn.bind("click", function () {
                var zTree = $.fn.zTree.getZTreeObj("treeDemo");
                // 新增的节点（随机uuid，并继承父类的uuid）
                var newTreeNode = {id: UUIDUtils.uuid(), pid: treeNode.id, name: "new node" + (newCount++)}
                zTree.addNodes(treeNode, newTreeNode);
                //increaseMethod(newTreeNode);
                return false;
            });
        };

        // 用于当鼠标移出节点时，隐藏用户自定义控件，显示隐藏状态同 zTree 内部的编辑、删除按钮
        function removeHoverDom(treeId, treeNode) {
            $("#addBtn_" + treeNode.tId).unbind().remove();
        };

        /**
         * 取得菜单树节点
         */
        function getNodesMethod() {
            $.ajax({
                url: "../../menus/menuTree",
                type: "GET",
                async: false,
                success: function (data) {
                    zNodes = JSON.parse(data);
                },
                error: function (res) {
                    layer.msg("数据获取失败");
                    return false;
                }
            })
        }

        /**
         * 增加菜单节点
         * @param treeNode
         */
        function increaseMethod(treeNode){
            $.ajax({
                url : "../../menus/treeNode",
                type : "POST",
                async : false,
                data : treeNode,
                success: function (data) {
                    zNodes = data;
                },
                error: function (res) {
                    layer.msg("新增失败");
                    return false;
                }
            })
        }

        /**
         * 菜单重命名
         * @param treeNode
         */
        function renameMethod(treeNode) {
            $.ajax({
                url: "../../menus/treeNode",
                type: "PUT",
                async: false,
                data: treeNode,
                success: function (data) {
                    zNodes = data;
                },
                error: function (res) {
                    layer.msg("修改失败");
                    return false;
                }
            })
        }

        /**
         * 菜单删除
         * @param treeNode
         */
        function removeMethod(treeNode) {
            $.ajax({
                url: "../../menus/" + treeNode.id,
                type: "DELETE",
                async: false,
                success: function (data) {
                    zNodes = data;
                },
                error: function (res) {
                    layer.msg("删除失败");
                    return false;
                }
            })
        }

    </script>
</head>
<body>
<div>
    <ul id="treeDemo" class="ztree"></ul>
</div>
<!--<div id="rMenu" style="z-index:100;">
    <ul>
        <li id="m_add" onclick="addTreeNode();">新增节点</li>
        <li id="m_del" onclick="removeTreeNode();">删除节点</li>
        <li id="m_edit" onclick="editTreeNode();" style="border-bottom:1px solid #cecece">编辑节点</li><li id="m_left">升级</li>
        <li id="m_right">降级</li>
        <li id="m_up">上移</li>
        <li id="m_down" style="border-bottom:1px solid #cecece">下移</li>
        <li id="m_reset" onclick="resetTree();">重置节点</li>
        <li id="m_open" onclick="treeOpen()">展开所有</li>
        <li id="m_stop" onclick="treeStop()">收起所有</li>
    </ul>
</div>-->
</body>
</html>